package cmd

import (
	"fmt"
	"path"
	"time"

	"cloudstation/store"
	"cloudstation/store/provider/aliyun"
	"cloudstation/store/provider/miniop"
	"cloudstation/user"
	"cloudstation/util"

	"github.com/spf13/cobra"
)

var (
	username string
	password string
)

// uploadCmd represents the start command
var singinCmd = &cobra.Command{
	Use:   "Supload",
	Short: "登录用户上传文件",
	Long:  "登录用户上传文件",
	RunE: func(cmd *cobra.Command, args []string) error {

		p,v, err := singingetProvider()
		if err != nil {
			return err
		}
		if uploadFilePath == "" {
			return fmt.Errorf("upload file path is missing")
		}
		day := time.Now().Format("20060102")
		fn := path.Base(uploadFilePath)
		ok := fmt.Sprintf("%s/%s", day, fn)
		err = p.UploadFile(v.BuckName, ok, uploadFilePath)
		if err != nil {
			return err
		}
		return nil
	},
}

func singingetProvider() (p store.Uploader,v *user.User, err error) {
	util.InputUserPassword(&username, &password)
	m, err := user.ReadData()
	if err != nil {
		return nil,&user.User{},err
	}
	v,ok := m[username]
	if !ok {
		return nil,&user.User{},fmt.Errorf("user not register!")
	}
	
	switch v.Provider {
	case "aliyun":
		fmt.Printf("上传云商: 阿里云[%s]\n", v.BucketEndpoint)
		fmt.Printf("上传用户: %s\n", v.AccessID)
		p,err :=  aliyun.NewUploader(v.BucketEndpoint, v.AccessID, v.AccessKey)
		return p,v,err
	case "minio":
		fmt.Printf("上传云商: MiNIO[%s]\n", v.BucketEndpoint)

		fmt.Printf("上传用户: %s\n", v.AccessID)
		p,err := miniop.NewUploader(v.BucketEndpoint, v.AccessID, v.AccessKey)
		return p,v,err

	default:
		return nil,&user.User{}, fmt.Errorf("unknown oss privier options [aliyun/minio]")
	}
}

func init() {
	singinCmd.PersistentFlags().StringVarP(&uploadFilePath, "file_path", "f", "", "upload file path")
	// uploadCmd.PersistentFlags().StringVarP(&buckName, "bucket_name", "b", "", "upload oss bucket name")
	// uploadCmd.PersistentFlags().StringVarP(&bucketEndpoint, "bucket_endpoint", "e", "", "upload oss endpoint")
	RootCmd.AddCommand(singinCmd)
}
